package com.jz.yanshe.ui;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.jz.jd.rest.business.RestProxy;
import com.jz.jd.rest.exception.BusinessException;
import com.jz.jd.rest.response.BaseResponse;

import com.jz.jd.rest.response.WeChatPayResponse;
import com.jz.yanshe.R;
import com.jz.yanshe.base.BaseActivity;
import com.jz.yanshe.base.BaseApplication;
import com.jz.yanshe.util.PreferencesHelper;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by liuwei on 2018/5/7.
 */

public class AlipayActivity extends BaseActivity implements View.OnClickListener {


    private Button btn_pay;
    private CheckBox checkbox_alipay, checkbox_wechat;
    private String orderid;
    private String deduct;
    private String vipGradeId;

    @Override
    protected void initViews() {
        btn_pay = findViewById(R.id.btn_pay);
        checkbox_alipay = findViewById(R.id.checkbox_alipay);
        checkbox_wechat = findViewById(R.id.checkbox_wechat);
        btn_pay.setOnClickListener(this);
        checkbox_alipay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(checkbox_alipay.isChecked()){
                    if(checkbox_wechat.isChecked()){
                        checkbox_wechat.setChecked(false);
                    }
                }
            }
        });
        checkbox_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(checkbox_wechat.isChecked()){
                    if(checkbox_alipay.isChecked()){
                        checkbox_alipay.setChecked(false);
                    }
                }
            }
        });
    }

    @Override
    protected void initData() {
        orderid = getIntent().getStringExtra("orderid");
        deduct = getIntent().getStringExtra("deduct");
        vipGradeId = getIntent().getStringExtra("gradeid");
        BaseApplication.api = WXAPIFactory.createWXAPI(this,BaseApplication.APP_ID_WX,true);
        BaseApplication.api.registerApp(BaseApplication.APP_ID_WX);
    }


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_alipay;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_pay:
                if (checkbox_alipay.isChecked()) {
                    RestProxy.getInstance().aliply(PreferencesHelper.getInstance().getString(this, "token"), orderid, vipGradeId, deduct,new Observer<BaseResponse>() {

                        @Override
                        public void onSubscribe(Disposable d) {
                        }

                        @Override
                        public void onNext(BaseResponse baseResponse) {
                            if (baseResponse.data instanceof String) {
                                final String orderInfo = (String) baseResponse.data;
//                                orderInfo = "app_id=2018031602390389&timestamp=2016-07-29+16%3A55%3A53&biz_content=%7B%22timeout_express%22%3A%2230m%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22total_amount%22%3A%220.01%22%2C%22subject%22%3A%221%22%2C%22body%22%3A%22%E6%88%91%E6%98%AF%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE%22%2C%22out_trade_no%22%3A%22051115595266261%22%7D&method=alipay.trade.app.pay&charset=utf-8&version=1.0&sign_type=RSA2&sign=J6EDDYYZYbxkBs%2F3bjdr4NIALeHEBRl942Epj58N%2BsxrvY0EbFPEkAsB8sOZo1pzcaAAt8k679RUrPddOU8Xc7y31PxNr2uOb5tB0LMdWfx35rZOAc7y0IDfx0YqVGtLZtYBn9qMzRZJYXWWgGQ5wDqp7AwpJlT5HZ%2FP4maXvOgZtHpuFYTgSJmWLLo4Ez9Yv7PA%2BG3SDOoCBH4TujSOD1vfGe5r7hNDiN%2FHddaPOt9LnYNYecXV9Y0NfuY5aQW1PjaccCC%2FBYX0vNVBexsbHTRCBtPwH%2FgU6cpRpg6fj9CrUoWbSKQNBUCxssurR5PXsXzR2Hb3RPvvxRBpGx2wSA%3D%3D";

                                Runnable runnable = new Runnable() {
                                    @Override
                                    public void run() {
                                        PayTask alipay = new PayTask(AlipayActivity.this);
                                        Map<String, String> result = alipay.payV2(orderInfo, true);
                                        if (result.get("resultStatus").equals("9000")) {
                                            AlipayActivity.this.runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(AlipayActivity.this, "付款成功", Toast.LENGTH_SHORT).show();
                                                }
                                            });

                                        } else if (result.get("resultStatus").equals("4000")) {
                                            AlipayActivity.this.runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(AlipayActivity.this, "付款失败", Toast.LENGTH_SHORT).show();
                                                }
                                            });
                                        } else if (result.get("resultStatus").equals("6001")) {
                                            AlipayActivity.this.runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(AlipayActivity.this, "取消付款", Toast.LENGTH_SHORT).show();
                                                }
                                            });


                                        }
                                        Bundle bundle = new Bundle();
                                        bundle.putInt("type",1);
                                        startActivity(MyOrderActivity.class,bundle);
                                        finish();
                                        Log.e("msg", result + "");
                                    }
                                };

                                Thread thread = new Thread(runnable);
                                thread.start();

                            }
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });


                } else if (checkbox_wechat.isChecked()) {
                        RestProxy.getInstance().wechatPay(PreferencesHelper.getInstance().getString(this, "token"), orderid, vipGradeId,deduct, new Observer<WeChatPayResponse>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(WeChatPayResponse weChatPayResponse) {
                                PayReq req = new PayReq();
                                req.appId = weChatPayResponse.appid;
                                req.partnerId = weChatPayResponse.partnerid;
                                req.prepayId = weChatPayResponse.prepayid;
                                req.nonceStr = weChatPayResponse.noncestr;
                                req.timeStamp = weChatPayResponse.timestamp;
                                req.packageValue = "Sign=WXPay";
                                req.sign = weChatPayResponse.sign;
                                // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                                //3.调用微信支付sdk支付方法
                                 BaseApplication.api.sendReq(req);
                                 finish();
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });
                } else {
                    Toast.makeText(this, "请选择支付方式", Toast.LENGTH_SHORT).show();
                }
                break;
        }

    }


}
